package org.fanjr.simplify.rest.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fanjr@vip.qq.com
 * @since 20190222 10:29:28
 */
public class SimplifyCounterUtil {

	private Map<String, Counter> storage;

	private SimplifyCounterUtil() {
		storage = new HashMap<>();
	}

	public static SimplifyCounterUtil newInstance() {
		return new SimplifyCounterUtil();
	}

	public int add(String name) {
		Counter counter = storage.get(name);
		if (null == counter) {
			counter = newCounter();
			storage.put(name, counter);
		}
		return counter.add();
	}

	public int now(String name) {
		Counter counter = storage.get(name);
		if (null == counter) {
			return 0;
		}
		return counter.now();
	}

	private Counter newCounter() {
		return new DefaultCounter();
	}

	public static class DefaultCounter implements Counter {

		int num = 0;

		@Override
		public int now() {
			return num;
		}

		@Override
		public int add() {
			return ++num;
		}

	}

	public static interface Counter {
		int now();

		int add();
	}
}
